package com.weifly.weistock.record.data.impl;

import com.weifly.weistock.core.common.StockException;
import com.weifly.weistock.core.util.HttpRequestUtils;
import com.weifly.weistock.core.util.WeistockUtils;
import com.weifly.weistock.record.data.DataMarketService;
import com.weifly.weistock.record.data.domain.StockDataDto;
import com.weifly.weistock.record.data.domain.StockDayDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * sina股票数据实现
 *
 * @author weifly
 * @since 2019/9/29
 */
public class SinaDataMarketServiceImpl implements DataMarketService {

    private Logger log = LoggerFactory.getLogger(SinaDataMarketServiceImpl.class);

    private Map<String, String> stockCodeMap = new HashMap<>();

    // https://quotes.sina.cn/cn/api/jsonp.php/var%20_sz1599152019_7_29=/KC_MarketDataService.getKLineData?symbol=sz159915
    public static final String URL_STOCK_DATA_1 = "https://quotes.sina.cn/cn/api/jsonp.php/var%20_";
    public static final String URL_STOCK_DATA_2 = "=/KC_MarketDataService.getKLineData?symbol=";

    public SinaDataMarketServiceImpl(){
        stockCodeMap.put("000001", "sh"); // 上证综指
        stockCodeMap.put("399001", "sz"); // 深圳成指
        stockCodeMap.put("399006", "sz"); // 创业板指数
    }

    @Override
    public StockDataDto loadStockData(String stockCode) {
        String fullCode = this.getFullCode(stockCode);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
        String fullUrl = URL_STOCK_DATA_1 + fullCode + sdf.format(new Date()) + URL_STOCK_DATA_2 + fullCode;
        // log.info("stock data url: " + fullUrl);

        String stockDataStr =  HttpRequestUtils.sendGet(fullUrl, "GBK");
        if(stockDataStr==null){
            return null;
        }
        int startIdx = stockDataStr.indexOf("(");
        if(startIdx==-1){
            return null;
        }
        int endIdx = stockDataStr.indexOf(")", startIdx+1);
        if(endIdx==-1){
            return null;
        }
        String targetStr = stockDataStr.substring(startIdx+1, endIdx);
        // log.info("data json : " + targetStr);
        List dayInfoList = WeistockUtils.toJsonObject(targetStr, List.class);

        StockDataDto dataDto = new StockDataDto();
        dataDto.setCode(stockCode);
        if(dayInfoList!=null){
            SimpleDateFormat sdfFrom = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfTo = new SimpleDateFormat("yyyyMMdd");
            for(int i=0;i<dayInfoList.size();i++){
                Map dayInfo = (Map)dayInfoList.get(i);
                StockDayDto dayDto = new StockDayDto();
                try{
                    String day = (String)dayInfo.get("d");
                    dayDto.setDay(sdfTo.format(sdfFrom.parse(day)));
                }catch(ParseException e){
                    throw new RuntimeException(e);
                }
                // 开盘价
                String openStr = (String)dayInfo.get("o");
                dayDto.setOpen(Double.parseDouble(openStr));
                // 最高价
                String highStr = (String)dayInfo.get("h");
                dayDto.setHigh(Double.parseDouble(highStr));
                // 最低价
                String lowStr = (String)dayInfo.get("l");
                dayDto.setLow(Double.parseDouble(lowStr));
                // 收盘价
                String closeStr = (String)dayInfo.get("c");
                dayDto.setClose(Double.parseDouble(closeStr));
                dataDto.getDayList().add(dayDto);
            }
        }
        return dataDto;
    }

    private String getFullCode(String stockCode){
        String fullCode = null;

        if(this.stockCodeMap.containsKey(stockCode)){
            fullCode = this.stockCodeMap.get(stockCode)+stockCode;
        }else if(stockCode.startsWith("6")){
            fullCode = "sh"+stockCode; // 上海股票
        }else if(stockCode.startsWith("5")){
            fullCode = "sh"+stockCode; // 上海ETF基金
        }else if(stockCode.startsWith("1")){
            fullCode = "sz"+stockCode; // 深圳ETF基金
        }else if(stockCode.startsWith("0") || stockCode.startsWith("3")){
            fullCode = "sz"+stockCode; // 深圳股票
        }else{
            throw new StockException("不支持证券代码：" + stockCode);
        }
        return fullCode;
    }
}
